package cloud.seata.warehouse.controller;

import cloud.seata.warehouse.repository.WarehouseRopository;
import cloud.seata.warehouse.repository.entity.Stockpile;
import cloud.seata.warehouse.tcc.TccWarehouseAction;
import org.apache.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Transactional
public class WarehouseController implements TccWarehouseAction {

    @Autowired
    private WarehouseRopository warehouseRopository;



    @Override
    public ResponseEntity<Boolean> prepare(BusinessActionContext actionContext) {
        Stockpile stockpile = warehouseRopository.selectById(1);

        Stockpile wh = new Stockpile();
        wh.setId(1);
        wh.setAmount(stockpile.getAmount()-9);
        wh.setFrozen(stockpile.getFrozen()+9);
        wh.setProduct_id(1);
        warehouseRopository.updateById(wh);
//        throw new Exception("库存不足");
        return ResponseEntity.status(HttpStatus.OK).body(Boolean.TRUE);
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {

        Stockpile stockpile = warehouseRopository.selectById(1);

        stockpile.setFrozen(stockpile.getFrozen()-9);
        warehouseRopository.updateById(stockpile);
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {

        Stockpile stockpile = warehouseRopository.selectById(1);

        stockpile.setFrozen(stockpile.getFrozen()-9);
        stockpile.setAmount(stockpile.getAmount()+9);
        warehouseRopository.updateById(stockpile);
        return true;
    }
}
